/**
 *
 * 下拉选择框组件
 *
 * */
import {ICellInputProps} from "@/biz-components/claim-items/components-v2/cell-input/ICellInputProps";
import {useEffect, useState} from "react";
import {Select} from "antd";
import * as React from "react";

export interface SelectorExtraProps {
	showSearch?: boolean;
	valueInLabel?: boolean;
	dataSource:
		| (() => Promise<Array<{ name: string; value: string }>>)
		| Array<{ name: string; value: string }>;
	style?: React.CSSProperties
}
export type SelectProps = SelectorExtraProps & ICellInputProps<string>;

export function Selector(props: SelectProps) {
	const {  valueInLabel = false , style = {}} = props;
	const [options, setOptions] = useState<Array<{ name: string; value: string }>>([]);

	useEffect(function () {
			if (typeof props.dataSource === 'function') {
				props.dataSource().then(setOptions);
			} else {
				setOptions(props.dataSource);
			}
		},
		[props.dataSource],
	);


	return (
		<Select<string>
			showSearch={props.showSearch}
			optionFilterProp={'children'}
			disabled={props.disabled}
			value={props.value}
			onChange={(v) => {
				const name = options.find((item) => item.value === v)?.name || '';
				props.onChange(v, name);
			}}
			allowClear
			style={{minWidth: "140px", ...style}}
		>
			{options.map((item) => (
				<Select.Option key={item.value} value={item.value}>
					{valueInLabel ? `${item.value}-${item.name}` : item.name}
				</Select.Option>
			))}
		</Select>
	);
}
Selector.defaultValue = '';
